package com.xxx.video.commen.utils;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;

import com.xxx.video.dynamic.beans.ContactBean;

import java.util.ArrayList;
import java.util.List;

public class ContactUtils {
    private static ContactUtils mContactUtils = null;

    private ContactUtils() {
    }

    public static ContactUtils getInstance() {
        if (mContactUtils == null) {
            synchronized (ContactUtils.class) {
                if (mContactUtils == null) {
                    mContactUtils = new ContactUtils();
                }
            }
        }
        return mContactUtils;
    }

    /**
     * get contact list
     *
     * @param context context
     * @return contact list
     */
    public List<ContactBean> getContactList(Context context) {
        List<ContactBean> contactBeanList = new ArrayList<>();
        Cursor profileCursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        while (profileCursor.moveToNext()) {

            String contactId = profileCursor.getString(profileCursor.getColumnIndex(ContactsContract.Contacts._ID));
            /*
             * name
             */
            String name = profileCursor.getString(profileCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            /*
             * get phone
             */
            Cursor phoneCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
            String phone = "";
            while (phoneCursor.moveToNext()) {
                /*
                 * get phone
                 */
                phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phone = phone.replace("-", "")
                        .replace(" ", "")
                        .replace("(", "")
                        .replace(")", "");
            }
            ContactBean contactBean = new ContactBean.Builder()
                    .name(name)
                    .phone(phone)
                    .build();
            contactBeanList.add(contactBean);
            phoneCursor.close();
        }
        profileCursor.close();
        return contactBeanList;
    }
}
